#-*-coding:utf-8-*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from ..items import BookItem


class BookSpider(scrapy.Spider):
    # ID
    name = "books"

    # start urls
    start_urls = ['http://books.toscrape.com/']

    def parse(self, response):
        # <article class="product_pod">
        for sel in response.css('article.product_pod'):
            book = BookItem()
            # <h3><a title="A Light in the Attic">A Light in the ...</a></h3>
            book['name'] = sel.xpath('./h3/a/@title').extract_first()
            #<div class="product_price"><p class="price_color">£51.77</p>
            book['price'] = sel.css('p.price_color::text').extract_first()

            yield book

        # <li class="next"><a href="catalogue/page-2.html">next</a></li>
        le = LinkExtractor(restrict_css=('ul.pager li.next'))
        links = le.extract_links(response)

        if links:
            next_url = links[0].url
            yield scrapy.Request(next_url, callback=self.parse)
